package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.test4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Resource
    private  IArticleClient iArticleClient;
    @Autowired
    private WmChannelService wmChannelService;
    @Autowired
    private  WmUserMapper wmUserMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews==null) {
            throw  new RuntimeException("该"+id+"文章不存在");
        }
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){

            Map<String,Object> textAndImages=handlerTextAndImages(wmNews);
              //审核文本，，，，ali接口
            //自管理文本
           if (!handleSensitiveScan((String) textAndImages.get("content"), wmNews)) {
                return;
            }


            //3.审核图片  阿里云接口+图片文字扫描
            boolean isImageScan =  handleImageScan((List<String>) textAndImages.get("images"),wmNews);
            if(!isImageScan)return;

            if(true){
                ResponseResult responseResult = saveAppArticle(wmNews);
                if(!responseResult.getCode().equals(200)){
                    throw  new RuntimeException("文章审核错误！");
                }
                wmNews.setArticleId((Long) responseResult.getData());
                updateWmNews(wmNews,(short)9,"审核通过");

            }

        }


    }
    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private Tess4jClient tess4jClient;

    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;

        if(images == null || images.size() == 0){
            return flag;
        }

        //下载图片 minIO
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();
        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                //图片识别
                ByteArrayInputStream in= new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(in);
                String result = tess4jClient.doOCR(bufferedImage);
              if (!handleSensitiveScan(result, wmNews)) {
                   return false;
                }
                imageList.add(bytes);
            }
        }catch (Exception e){
            e.printStackTrace();
        }



        //阿里审核图片
//        try {
//            Map map = greenImageScan.imageScan(imageList);
//            if(map != null){
//                //审核失败
//                if(map.get("suggestion").equals("block")){
//                    flag = false;
//                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
//                }
//
//                //不确定信息  需要人工审核
//                if(map.get("suggestion").equals("review")){
//                    flag = false;
//                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
//                }
//            }

//        } catch (Exception e) {
//            flag = false;
//            e.printStackTrace();
//        }
        return flag;
    }

    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitivesList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitivesList);
        Map<String, Integer> resMap = SensitiveWordUtil.matchWords(wmNews.getTitle() + content);
        if(resMap.size()>0){
            updateWmNews(wmNews, (short) 2,"当前文章存在违规内容"+resMap);
            return false;
        }

        return true;
    }

    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        if(wmChannel!=null){
            dto.setChannelName(wmChannel.getName());

        }
        dto.setAuthorId(Long.valueOf(wmNews.getUserId()));
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }
        if (wmNews.getArticleId()!=null) {
            dto.setId(wmNews.getArticleId());

        }
        dto.setCreatedTime(new Date());
        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        return responseResult;
    }

    private Map<String, Object> handlerTextAndImages(WmNews wmNews) {
        StringBuilder text=new StringBuilder();
        List<String> images = new ArrayList<>();

        if (StringUtils.isNotBlank( wmNews.getContent())) {
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if(map.get("type").equals("text")) {
                    text.append(map.get("value"));
                }
                if(map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }
        }


        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content",text.toString());
        hashMap.put("images",images);
        return  hashMap;
    }
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }
}
